﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;
using System.Data.SqlTypes;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace Department.admin.Content
{
    public partial class EditLecturer : System.Web.UI.Page
    {
        int lectID = -1;
        string linkToDelete = null;
        private string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;
        const int MAX_FILE_SIZE = AdminVariablesSingleton.MAX_FILE_SIZE;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.IsAuthenticated)
            {
                Response.Redirect("/admin/Login.aspx");
            }
            if (Request.Params["ID"] == null) // Redirect user if the page is loaded without params
            {
                Response.Redirect("/admin/Content/ViewAllLecturers.aspx");
            }

            this.Page.Title = "Редакция на събитие";

            AdminVariablesSingleton.configureCKEditor(ref TextBoxText);

            string office = null;
            string telephone = null;
            string email = null;
            string page = null;
            string text = null;
            
            bool isHidden=false;
            string id = Request.Params["ID"];
            if (!Page.IsPostBack)
            {
                if (!(id == null))
                {
                    SqlConnection conn = new SqlConnection(strConnString);

                    try
                    {
                        conn.Open();

                        //Gets the news heading
                        string sqlHeading = "SELECT Lecturers.Office, Lecturers.Phone, Lecturers.Email, Lecturers.PersonalHomePage, ISNULL(Lecturers.IsHidden, 0) AS IsHidden, ISNULL(Lecturers.ID,-1) AS ID, LecturersFromDB.LecturerID, Lecturers.LecturerDbID, Lecturers.Info, Lecturers.PictureLink,LecturersFromDB.LecturerFullNameBG FROM Lecturers RIGHT OUTER JOIN LecturersFromDB ON Lecturers.LecturerDbID = LecturersFromDB.LecturerID WHERE LecturersFromDB.LecturerID = @ID";
                        SqlCommand comHeading = new SqlCommand(sqlHeading, conn);
                        comHeading.Parameters.AddWithValue("@ID", id);
                        SqlDataReader reader = comHeading.ExecuteReader();

                        while (reader.Read())
                        {
                            try
                            {
                                office = reader.GetString(0);
                                telephone = reader.GetString(1);
                                email = reader.GetString(2);
                                page = reader.GetString(3);
                                isHidden = reader.GetBoolean(4);
                                text = reader.GetString(8);
                                linkToDelete = reader.GetString(9);
                                nameLabel.Visible = true;
                                nameLabel.Text = reader.GetString(10);
                            }
                            catch (SqlNullValueException ec)
                            {
                                ec.ToString();
                                errorLabel.Text = "Възникна проблем, опитайте отново!";
                            }          
                        }
                        TextBoxOffice.Text = office;
                        TextBoxTelephone.Text = telephone;
                        TextBoxEmail.Text = email;
                        TextBoxPage.Text = page;
                        checkboxActive.Checked = isHidden;
                        TextBoxText.Text = text;
                    }
                    catch (SqlException sqle)
                    {
                        Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
                    }
                    catch (Exception ex)
                    {
                        Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
                    }
                    finally
                    {
                        conn.Close();
                    }

                }

            }

        }

        protected void buttonSubmit_Click(object sender, EventArgs e)
        {
            SqlConnection conn2 = new SqlConnection(strConnString);
            string idFromLecturersView = Request.Params["id"];
            try
            {
                conn2.Open();
                string sqlHeading = "SELECT Lecturers.Office, Lecturers.Phone, Lecturers.Email, Lecturers.PersonalHomePage, ISNULL(Lecturers.IsHidden, 0) AS IsHidden, ISNULL(Lecturers.ID,-1) AS ID, LecturersFromDB.LecturerID, Lecturers.LecturerDbID, Lecturers.Info, Lecturers.PictureLink FROM Lecturers RIGHT OUTER JOIN LecturersFromDB ON Lecturers.LecturerDbID = LecturersFromDB.LecturerID WHERE LecturersFromDB.LecturerID = @ID";
                SqlCommand comHeading = new SqlCommand(sqlHeading, conn2);
                comHeading.Parameters.AddWithValue("@ID", idFromLecturersView);
                SqlDataReader reader = comHeading.ExecuteReader();

                while (reader.Read())
                {
                    try
                    {

                        linkToDelete = reader.GetString(9);
                    }
                    catch (SqlNullValueException ec)
                    {
                        ec.ToString();
                    }
                    try
                    {
                        lectID = Convert.ToInt32(reader.GetValue(5));
                    }
                    catch (InvalidCastException exc)
                    {
                        lectID = -1;
                        exc.ToString();
                    }

                }
            }
            catch (SqlException sqle)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
            }
            catch (Exception ex)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
            }
            finally
            {
                conn2.Close();
            }


            SqlConnection conn = new SqlConnection(strConnString);
            try
            {
                conn.Open();
                string sqlUpdate;
                SqlCommand comUpdate = null;
                if (lectID != -1)
                {
                    sqlUpdate = "UPDATE Lecturers SET PictureLink =@Link, Office =@Office, Phone =@Phone, Email =@Email, Info =@Info, PersonalHomePage =@PHP, IsHidden =@IsHidden WHERE ID = @ID";
                    
                   
                    comUpdate = new SqlCommand(sqlUpdate, conn);

                  
                    comUpdate.Parameters.AddWithValue("@ID", lectID);
                    comUpdate.Parameters.AddWithValue("@Office", TextBoxOffice.Text);
                    comUpdate.Parameters.AddWithValue("@Phone", TextBoxTelephone.Text);
                    comUpdate.Parameters.AddWithValue("@IsHidden", checkboxActive.Checked);
                    comUpdate.Parameters.AddWithValue("@Email", TextBoxEmail.Text);
                    comUpdate.Parameters.AddWithValue("@Info", TextBoxText.Text);
                    comUpdate.Parameters.AddWithValue("@PHP", TextBoxPage.Text);


                    FileInfo link = uploadFile(FileUploadControl, true);
                    if (link != null)
                    {
                        comUpdate.Parameters.AddWithValue("@Link", link.FilePath);

                    }
                
                }
                else
                {
                    sqlUpdate = "INSERT INTO Lecturers (Office, Phone, Email, Info, PersonalHomePage, PictureLink, LecturerDbID) VALUES (@Office, @Phone, @Email, @Info, @PHP, @Link, @LectDBID)";


                    comUpdate = new SqlCommand(sqlUpdate, conn);


                    comUpdate.Parameters.AddWithValue("@ID", lectID);
                    comUpdate.Parameters.AddWithValue("@Office", TextBoxOffice.Text);
                    comUpdate.Parameters.AddWithValue("@Phone", TextBoxTelephone.Text);
                    comUpdate.Parameters.AddWithValue("@IsHidden", checkboxActive.Checked);
                    comUpdate.Parameters.AddWithValue("@Email", TextBoxEmail.Text);
                    comUpdate.Parameters.AddWithValue("@Info", TextBoxText.Text);
                    comUpdate.Parameters.AddWithValue("@PHP", TextBoxPage.Text);
                    comUpdate.Parameters.AddWithValue("@LectDBID", idFromLecturersView);

                    FileInfo link = uploadFile(FileUploadControl, false);
               

                    if (link != null)
                    {
                        comUpdate.Parameters.AddWithValue("@Link", link.FilePath);
                    }
                    else
                    {
                        sqlUpdate = "INSERT INTO Lecturers (Office, Phone, Email, Info, PersonalHomePage, LecturerDbID) VALUES (@Office, @Phone, @Email, @Info, @PHP, @LectDBID)";
                        comUpdate.CommandText = sqlUpdate;
                    }


                }
                


                comUpdate.ExecuteNonQuery();

            }
            catch (SqlException sqle)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
            }
            catch (Exception ex)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
            }
            finally
            {
                conn.Close();
            }
           
            Response.Redirect("~/admin/Content/ViewAllLecturers.aspx");
        }
        protected FileInfo uploadFile(FileUpload fileControl, bool deleteOldFile)
        {
            if (fileControl.HasFile)
            {
                try
                {
                    if (fileControl.PostedFile.ContentLength < MAX_FILE_SIZE)
                    {
                        FileInfo fileInfo = new FileInfo();
                        string filename = Path.GetFileName(fileControl.FileName);
                        fileInfo.OriginalFileName = filename;

                        filename = DateTime.Now.ToUniversalTime().ToFileTimeUtc() + filename;
                        fileInfo.UniqueFileName = filename;


                        fileInfo.FilePath ="~/files/Lecturers/Images/" + filename + ".png";


                        byte[] imageByteArray = PrepImageForUpload(fileControl.FileContent);

                                                
                        MemoryStream ms = new MemoryStream(imageByteArray);
                        System.Drawing.Image i = System.Drawing.Image.FromStream(ms);
                        i.Save(Server.MapPath("~/files/Lecturers/Images/") + filename + ".png", System.Drawing.Imaging.ImageFormat.Png);
                         
                        
                        

                        

                        if (deleteOldFile)
                        {
                            System.IO.File.Delete(Server.MapPath(linkToDelete));
                        }

                        return fileInfo;
                    }
                }
                catch (Exception ex)
                {
                    Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
                }
            }
            return null;
        }            
        
        protected void markInactiveButton_Click(object sender, CommandEventArgs e)
        {
            string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(strConnString);
            try
            {
                conn.Open();
                string sqlCommandText = "DELETE FROM DocumentsForEvents FROM DocumentsForEvents WHERE DocID = @DocID; DELETE FROM Documents WHERE ID = @DocID";
                SqlCommand insertDocument = new SqlCommand(sqlCommandText, conn);

                insertDocument.Parameters.AddWithValue("@DocID", e.CommandArgument);


                insertDocument.ExecuteNonQuery();

            }
            catch (SqlException sqle)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
            }
            catch (Exception ex)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
            }
            finally
            {
                conn.Close();
            }

        }

        private static void markAnItemInactive(string ID)
        {
            string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(strConnString))
            {
                try
                {
                    conn.Open();

                    //Get Site content
                    string sqlText = "UPDATE Events SET IsHidden=1 WHERE ID = @ID";
                    SqlCommand comText = new SqlCommand(sqlText, conn);
                    comText.Parameters.AddWithValue("@ID", ID);

                    comText.ExecuteNonQuery();
                }
                catch (SqlException sqle)
                {
                   sqle.ToString();
                }
                finally
                {
                    conn.Close();
                }
            }
        }
        private byte[] PrepImageForUpload(Stream FileData)
        {
            using (Bitmap origImage = new Bitmap(FileData))
            {
                int maxWidth = 165;

                int newWidth = 100;
                int newHeight = 139;
                if (origImage.Width < newWidth) //Force to max width
                {
                    newWidth = maxWidth;
                    newHeight = origImage.Height * maxWidth / origImage.Width;
                }

                using (Bitmap newImage = new Bitmap(newWidth, newHeight))
                {
                    using (Graphics gr = Graphics.FromImage(newImage))
                    {
                        gr.SmoothingMode = SmoothingMode.AntiAlias;
                        gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        gr.DrawImage(origImage, new Rectangle(0, 0, newWidth, newHeight));

                        MemoryStream ms = new MemoryStream();
                        newImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                        return ms.ToArray();
                    }
                }
            }
        }
    }
}